package com.km.wskj.itmonitor.pager.wq.wscollege;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.fingdo.statelayout.StateLayout;
import com.km.wskj.itmonitor.R;
import com.km.wskj.itmonitor.global.ClassifyParams;
import com.km.wskj.itmonitor.http.ZxlGenericsCallback;
import com.km.wskj.itmonitor.model.CollegeItem;
import com.km.wskj.itmonitor.model.FuncItem;
import com.km.wskj.itmonitor.model.KnowledgeLibrary;
import com.km.wskj.itmonitor.pager.base.LActivity;
import com.km.wskj.itmonitor.pager.wq.ClassifyActivity;
import com.km.wskj.itmonitor.utils.CustomShareListener;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;
import com.umeng.socialize.shareboard.SnsPlatform;
import com.umeng.socialize.utils.ShareBoardlistener;
import com.zxl.zxlapplibrary.adapter.BaseAdapterHelper;
import com.zxl.zxlapplibrary.global.Constant;
import com.zxl.zxlapplibrary.util.LogUtils;
import com.zxl.zxlapplibrary.view.MyGridView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.finalteam.toolsfinal.AppCacheUtils;
import es.dmoral.toasty.Toasty;
import okhttp3.Call;
import zrc.widget.SimpleFooter;
import zrc.widget.SimpleHeader;
import zrc.widget.ZrcListView;

/**
 * @author by Xianling.Zhou on 2017/3/21.
 */
//微数学院主页面
public class CollegeActivity extends LActivity implements StateLayout.OnViewRefreshListener {
    private static final String TAG = "CollegeActivity";
    //ui
    @BindView(R.id.tool_bar_back)
    ImageView toolBarBack;
    @BindView(R.id.tool_bar_title)
    TextView toolBarTitle;
    @BindView(R.id.tool_bar_right)
    ImageView toolBarRight;
    LinearLayout mContainer;
    @BindView(R.id.zrcListView)
    ZrcListView mZrcListView;
    @BindView(R.id.state_layout)
    StateLayout stateLayout;
    //data
    private List<String> imgUrls = new ArrayList<>();
    private MyGridView gridView;
    List<FuncItem> funcItems = new ArrayList<>();
    private MyAdapter mAdapter;
    private int pageIndex;
    private int lastUpdateNum;
    private List<CollegeItem> mCollegeLists;
    private Intent intent;

    private List<KnowledgeLibrary> knowledgeLibrarys;
    private ShareAction mShareAction;
    private AppCacheUtils cacheUtils;
    private CollegeItem item;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ws_college);
        ButterKnife.bind(this);

        toolBarTitle.setText("微学院");
        toolBarBack.setVisibility(View.VISIBLE);
        toolBarRight.setVisibility(View.VISIBLE);
        toolBarRight.setImageResource(R.mipmap.search_white);

        initData();
        initFuncItems();
        initShare();

        pdc.knowledgeLib(HTTP_TASK_TAG, null, new ZxlGenericsCallback<List<KnowledgeLibrary>>() {
            @Override
            public void onError(Call call, Exception e, int i) {
                LogUtils.e(TAG, e);
            }

            @Override
            public void onResponse(List<KnowledgeLibrary> knowledgeLibraries, int i) {
                knowledgeLibrarys = knowledgeLibraries;
            }
        });
    }

    private void initData() {
        stateLayout.showLoadingView();
        pdc.collegeList(HTTP_TASK_TAG, null, 1, Constant.PageListSize, new ZxlGenericsCallback<List<CollegeItem>>() {
            @Override
            public void onError(Call call, Exception e, int i) {
                LogUtils.e(TAG, e);
                stateLayout.showErrorView();
            }

            @Override
            public void onResponse(List<CollegeItem> collegeLists, int i) {
                if (collegeLists.size() == 0)
                    stateLayout.showEmptyView();

                mCollegeLists = collegeLists;
                lastUpdateNum = collegeLists.size();
                pageIndex = 1;
                //control
                mAdapter.notifyDataSetChanged();
                mZrcListView.setRefreshSuccess();

                if (haveMore())
                    mZrcListView.startLoadMore();
                else
                    mZrcListView.stopLoadMore();
            }
        });

        initPullToRefresh();
    }

    private void initFuncItems() {
        String s[] = getResources().getStringArray(R.array.ws_college_func_title);
        int r[] = {R.mipmap.monitor_application
                , R.mipmap.monitor_database
                , R.mipmap.monitor_memory
                , R.mipmap.monitor_internet
                , R.mipmap.all
        };
        funcItems.clear();
        for (int i = 0; i < s.length && i < r.length; i++) {
            FuncItem fi = new FuncItem();
            fi.name = s[i];
            fi.resId = r[i];
            funcItems.add(fi);
        }
    }


    private void createGridView() {
        gridView = new MyGridView(context, new MyGridView.MyGridViewAdapter() {
            @Override
            public int rowspacing(MyGridView myGridView) {
                return 0;
            }

            @Override
            public int colspacing(MyGridView myGridView) {
                return 0;
            }

            @Override
            public int leftpadding(MyGridView myGridView) {
                return 0;
            }

            @Override
            public int toppadding(MyGridView myGridView) {
                return 0;
            }

            @Override
            public int colCount(MyGridView myGridView) {
                return 5;
            }

            @Override
            public int rowHeight(MyGridView myGridView) {
                return mContainer.getHeight() / 1;
            }

            @Override
            public int viewWidth(MyGridView myGridView) {
                return mContainer.getWidth();
            }

            @Override
            public int count(MyGridView myGridView) {
                return funcItems.size();
            }

            @Override
            public View cell(int i, MyGridView myGridView) {
                View view = getLayoutInflater().inflate(R.layout.ws_college_item_func, null);
                ImageView iv_pic = (ImageView) view.findViewById(R.id.iv_pic);
                TextView tv_name = (TextView) view.findViewById(R.id.tv_name);

                FuncItem fi = funcItems.get(i);
                iv_pic.setImageResource(fi.resId);
                tv_name.setText(fi.name);
                return view;
            }

            @Override
            public View title(int i, MyGridView myGridView) {
                return null;
            }

            @Override
            public int titleOffsetY(MyGridView myGridView) {
                return 0;
            }

            @Override
            public boolean needGridLine(MyGridView myGridView) {
                return false;
            }
        });


        gridView.setListener(new MyGridView.MyGridViewListener() {
            @Override
            public void onCellTouchDown(int i) {

            }

            @Override
            public void onCellTouchUp(int i) {

            }

            @Override
            public void onCellLongPress(int i) {

            }

            @Override
            public void onCellClick(int i) {
                switch (i) {
                    //操作系统
                    case 0: {
                        KnowledgeLibrary item = getCurrentItem("操作系统");
                        intent = new Intent(context, CollegeTabListActivity.class);
                        intent.putExtra("data", item);
                        startActivity(intent);
                    }
                    break;
                    //数据库
                    case 1: {
                        KnowledgeLibrary item = getCurrentItem("数据库");
                        intent = new Intent(context, CollegeTabListActivity.class);
                        intent.putExtra("data", item);
                        startActivity(intent);
                    }
                    break;
                    //存储
                    case 2: {
                        KnowledgeLibrary item = getCurrentItem("存储");
                        intent = new Intent(context, CollegeTabListActivity.class);
                        intent.putExtra("data", item);
                        startActivity(intent);
                    }
                    break;
                    //网络
                    case 3: {
                        KnowledgeLibrary item = getCurrentItem("网络");
                        intent = new Intent(context, CollegeTabListActivity.class);
                        intent.putExtra("data", item);
                        startActivity(intent);
                    }
                    break;
                    //全部
                    case 4: {
                        Intent t = new Intent(context, ClassifyActivity.class);
                        t.putExtra("index", ClassifyParams.COLLEGE_ALL);
                        startActivity(t);
                    }
                }
            }
        });
        LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        mContainer.addView(gridView.getView(), p);
    }


    private void initPullToRefresh() {
        //添加头布局
        View view = getLayoutInflater().inflate(R.layout.header_college, null);
        mContainer = (LinearLayout) view.findViewById(R.id.container_gridview);
        mContainer.removeAllViews();
        initFuncItems();

        mContainer.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                mContainer.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                createGridView();
            }
        });
        if (mZrcListView.getHeaderViewsCount() == 0)
            mZrcListView.addHeaderView(view, null, true);//注意：第三个参数必须为true，否则无效


        //配置listview
        ColorDrawable line = new ColorDrawable(Color.parseColor("#f1f1f1"));
        mZrcListView.setDivider(line);
        mZrcListView.setDividerHeight(1);

        //设置下拉刷新的样式（可选，但如果没有Header则无法下拉刷新）
        SimpleHeader header = new SimpleHeader(context);
        header.setTextColor(ContextCompat.getColor(context, R.color.text_gray));
        header.setCircleColor(ContextCompat.getColor(context, R.color.colorPrimary));
        mZrcListView.setHeadable(header);

        //设置加载更多的样式（可选）
        SimpleFooter footer = new SimpleFooter(context);
        footer.setCircleColor(ContextCompat.getColor(context, R.color.colorPrimary));
        mZrcListView.setFootable(footer);

        // 设置列表项出现动画（可选）
        //zListView.setItemAnimForTopIn(R.anim.topitem_in);
        mZrcListView.setItemAnimForBottomIn(R.anim.bottomitem_in);

        // 下拉刷新事件回调（可选）
        mZrcListView.setOnRefreshStartListener(new ZrcListView.OnStartListener() {
            @Override
            public void onStart() {
                onRefresh();
            }
        });

        // 加载更多事件回调（可选）
        mZrcListView.setOnLoadMoreStartListener(new ZrcListView.OnStartListener() {
            @Override
            public void onStart() {
                onLoadMore();
            }
        });

        // 项目选中
        mZrcListView.setOnItemClickListener(new ZrcListView.OnItemClickListener() {
            @Override
            public void onItemClick(ZrcListView parent, View view, int position, long id) {
                //用来保存分享情况，后面保存到服务器
                cacheUtils = AppCacheUtils.getInstance(context, "ws_college_share_msg");
                item = (CollegeItem) parent.getItemAtPosition(position);
                //默认没有分享过
                if (!cacheUtils.getBoolean(item.id, false)) {
                    normalToasty("分享后播放视频");
                    mShareAction.open();
                    return;
                }

                Intent t = new Intent(context, CollegeDetailActivity.class);
                t.putExtra("data", item);
                startActivity(t);
            }
        });

        mAdapter = new MyAdapter();
        mZrcListView.setAdapter(mAdapter);

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                stateLayout.showContentView();
            }
        }, 500);
    }

    private void initShare() {
        /*增加自定义按钮的分享面板*/
        mShareAction = new ShareAction(context).setDisplayList(
                SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE,
                SHARE_MEDIA.QQ, SHARE_MEDIA.QZONE
        )
                .setShareboardclickCallback(new ShareBoardlistener() {
                    @Override
                    public void onclick(SnsPlatform snsPlatform, SHARE_MEDIA share_media) {
                        UMWeb web = new UMWeb("http://fir.im/wsipos");
                        web.setTitle("来自IT智慧运维");
                        web.setDescription(item.desc);
                        web.setThumb(new UMImage(context, R.mipmap.logo_2));
                        new ShareAction(context).withMedia(web)
                                .setPlatform(share_media)
                                .setCallback(new MyShareListener())
                                .share();
                    }
                });
    }

    class MyShareListener implements UMShareListener {

        @Override
        public void onStart(SHARE_MEDIA share_media) {

        }

        @Override
        public void onResult(SHARE_MEDIA platform) {
            if (platform.name().equals("WEIXIN_FAVORITE")) {
                Toasty.success(context, platform + " 收藏成功啦", Toast.LENGTH_SHORT, false).show();
            } else {
                if (platform != SHARE_MEDIA.MORE && platform != SHARE_MEDIA.SMS
                        && platform != SHARE_MEDIA.EMAIL
                        && platform != SHARE_MEDIA.FLICKR
                        && platform != SHARE_MEDIA.FOURSQUARE
                        && platform != SHARE_MEDIA.TUMBLR
                        && platform != SHARE_MEDIA.POCKET
                        && platform != SHARE_MEDIA.PINTEREST

                        && platform != SHARE_MEDIA.INSTAGRAM
                        && platform != SHARE_MEDIA.GOOGLEPLUS
                        && platform != SHARE_MEDIA.YNOTE
                        && platform != SHARE_MEDIA.EVERNOTE) {
                    Toasty.success(context, platform + " 分享成功啦", Toast.LENGTH_SHORT, false).show();
                    cacheUtils.put(item.id, true);
                }

            }
        }

        @Override
        public void onError(SHARE_MEDIA share_media, Throwable throwable) {

        }

        @Override
        public void onCancel(SHARE_MEDIA share_media) {

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /** attention to this below ,must add this**/
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    private void onRefresh() {
        pdc.collegeList(HTTP_TASK_TAG, null, 1, Constant.PageListSize, new ZxlGenericsCallback<List<CollegeItem>>() {
            @Override
            public void onError(Call call, Exception e, int i) {
                LogUtils.e(TAG, e);
                stateLayout.showErrorView();
            }

            @Override
            public void onResponse(List<CollegeItem> collegeLists, int i) {
                if (collegeLists.size() == 0)
                    stateLayout.showEmptyView();

                mCollegeLists = collegeLists;
                lastUpdateNum = collegeLists.size();
                pageIndex = 1;
                //control
                mAdapter.notifyDataSetChanged();
                mZrcListView.setRefreshSuccess();

                if (haveMore())
                    mZrcListView.startLoadMore();
                else
                    mZrcListView.stopLoadMore();
            }
        });
    }

    private void onLoadMore() {
        pdc.collegeList(HTTP_TASK_TAG, null, pageIndex + 1, Constant.PageListSize, new ZxlGenericsCallback<List<CollegeItem>>() {
            @Override
            public void onError(Call call, Exception e, int i) {
                LogUtils.e(TAG, e);
            }

            @Override
            public void onResponse(List<CollegeItem> collegeLists, int i) {

                lastUpdateNum = collegeLists.size();
                if (collegeLists.size() > 0) {
                    mCollegeLists.addAll(collegeLists);
                    pageIndex++;
                }
                //control
                mAdapter.notifyDataSetChanged();
                mZrcListView.setLoadMoreSuccess();
                if (haveMore())
                    mZrcListView.startLoadMore();
                else
                    mZrcListView.stopLoadMore();

            }
        });
    }

    private boolean haveMore() {
        return lastUpdateNum > 0;
    }

    //点击重试
    @Override
    public void refreshClick() {

    }

    @Override
    public void loginClick() {

    }

    /**
     * 适配器
     */
    private class MyAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            if (mCollegeLists == null) {
                return 0;
            }
            return mCollegeLists.size();
        }

        @Override
        public Object getItem(int position) {
            return mCollegeLists.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public int getViewTypeCount() {
            return 1;
        }

        @Override
        public int getItemViewType(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            final BaseAdapterHelper helper = BaseAdapterHelper.get(context, convertView, parent, R.layout.item_college_list);
            CollegeItem item = mCollegeLists.get(position);
            helper.setText(R.id.tv_title, item.title);
            helper.setText(R.id.tv_des, item.desc);
            helper.setText(R.id.tv_create_time, item.createTime);

            //图片url
            CollegeItem.CoverImgBean coverImg = item.coverImg;
            if (coverImg != null) {
                String url = coverImg.host + coverImg.filePath + coverImg.newFileName;
                Glide.with(CollegeActivity.this)
                        .load(url)
                        .asBitmap()
                        .into(new SimpleTarget<Bitmap>() {
                            @Override
                            public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                                helper.setImageBitmap(R.id.iv_preview, resource);
                            }

                            @Override
                            public void onLoadFailed(Exception e, Drawable errorDrawable) {
                                super.onLoadFailed(e, errorDrawable);
                                LogUtils.e("LLpp:加载失败");
                            }
                        }); //方法中设置asBitmap可以设置回调类型
            }
            return helper.getView();
        }
    }

    private KnowledgeLibrary getCurrentItem(String itemName) {
        for (KnowledgeLibrary klb : knowledgeLibrarys
                ) {
            if (klb.columnName.equals(itemName))
                return klb;
        }
        return null;
    }

    @OnClick({R.id.tool_bar_back, R.id.tool_bar_right})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tool_bar_back:
                finish();
                break;
            case R.id.tool_bar_right:
                Toast.makeText(context, "搜索", Toast.LENGTH_SHORT).show();
                break;
        }
    }
}
